import { LOG } from 'koacat'
import WebSocket, { WebSocketServer } from 'ws'
import { App } from '../../app'

export class WSS {
  static singleton: WSS

  static createWebSocketServer(app: App) {
    const wss = new WebSocketServer({ port: app.config.WEBSOCKET_PORT })
    wss.on('connection', function connection(ws) {
      ws.on('error', (_ , error) => LOG(error))
      ws.on('message', function message(data, isBinary) {
        LOG(data.toString())
        wss.clients.forEach(function each(client) {
          if (client !== ws && client.readyState === WebSocket.OPEN) {
            client.send(data, { binary: isBinary })
          }
        })
      })
    })
    WSS.singleton = wss
  }
}